package com.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.hibernate.HibernateSessionFactory;
import com.model.Customerserver;

/**
 * 对CustomerServer模型进行增删改查操作的类
 *  
 * @author 0912652
 */

public class CustomerServerDao {

	public void insert(Customerserver Cs){
		// 获得Session，用来和数据库发起交互！
		Session session = HibernateSessionFactory.getSession();
		try {
			// 开启事务
			session.beginTransaction();
			// 保存数据
			session.save(Cs);
			// 提交事务
			session.getTransaction().commit();
		} catch (Exception e) {
			// 发生错误时，回滚到出事状态！
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			// 关闭Session
			HibernateSessionFactory.closeSession();
		}
	}
	
	public Customerserver checkCustServer(String snum, String pwd) {
		// 从数据库查询校对
		Session session = HibernateSessionFactory.getSession();
		try {
			session.beginTransaction();
			Criteria cri = session.createCriteria(Customerserver.class);
			cri.add(Restrictions.eq("snum", snum));
			cri.add(Restrictions.eq("pwd", pwd));
			Customerserver custServer = (Customerserver) cri.uniqueResult();

			session.saveOrUpdate(custServer);
			session.getTransaction().commit();
			return custServer;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		} finally {
			HibernateSessionFactory.closeSession();
		}

	}
	
	public List<Customerserver> findAll(){
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(Customerserver.class);
		
		List<Customerserver> list = criteria.list();
				
		return list;
	}
	
	public Customerserver findById(int sid){
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(Customerserver.class);
		
		criteria.add(Restrictions.eq("sid", sid));
		Customerserver cs = (Customerserver) criteria.uniqueResult();
		return cs;
	}
	
	
}
